import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_scan_tool/bloc/device/device_bloc.dart';
import 'package:flutter_scan_tool/clip/bottom_clipper.dart';
import 'package:flutter_scan_tool/db/dio_manage.dart';
import 'package:flutter_scan_tool/models/app_theme.dart';
import 'package:flutter_scan_tool/models/tool.dart';
import 'package:flutter_scan_tool/utils/flash_helper.dart';
import 'package:flutter_svg/svg.dart';

class ToolScanPage extends StatefulWidget {
  ToolScanPage({Key? key,required this.list}) : super(key: key);

  List<ToolData> list;

  @override
  State<ToolScanPage> createState() => _ToolScanPageState();
}

class _ToolScanPageState extends State<ToolScanPage> {
  @override
  void initState() {
    super.initState();
    bloc = context.read<DeviceBloc>();
  }

  DeviceBloc? bloc;

  final List<int> temp = [];
  final int temp1 = 1;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppTheme.appTheme.containerBackgroundColor(),
      floatingActionButton:
      BlocBuilder<DeviceBloc, DeviceState>(builder: (_, state) {
        return FloatingActionButton(
          onPressed: () {
            bloc!.add(DeviceFetchCompleteEvent());
          },
          child: Text(
              state.operateType ==0 ? '入库' : '出库'),
        );
      }),
      body: Stack(
        children: [
          ClipPath(
            clipper: BottomClipper(),
            child: Container(
              decoration: BoxDecoration(
                  gradient: AppTheme.appTheme.containerGradient(
                    begin: Alignment.centerLeft,
                    end: Alignment.centerRight,
                  )),
              height: 240,
            ),
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              SizedBox(
                height: MediaQuery
                    .of(context)
                    .viewPadding
                    .top,
              ),
              Container(
                margin: const EdgeInsets.only(left: 16, top: 16),
                child: BlocBuilder<DeviceBloc, DeviceState>(
                    buildWhen: (previousState, currentState) {
                      return previousState.notice != currentState.notice ||
                          previousState.toolKitId != currentState.toolKitId||previousState.operateType!=currentState.operateType;
                    },
                    builder: (context, state) {
                      String operateName = state.operateType ==0 ? '入库' : '出库';
                      return Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Padding(
                            padding:const EdgeInsets.only(left: 5.0),
                            child: Text( '工具柜:${bloc!.toolKitName ?? ''}',
                              style: AppTheme.appTheme.headline1(textColor: Colors
                                  .white, fontSize: 20, fontWeight: FontWeight
                                  .normal),),
                          ),
                          Text(
                            '操作:$operateName',
                            style: AppTheme.appTheme.headline1(
                                textColor: Colors.white,
                                fontSize: 20,
                                fontWeight: FontWeight.normal),
                          ),
                          Padding(
                            padding:const EdgeInsets.only(right: 10.0),
                            child: Text('提示信息:${state.notice}',
                              style: AppTheme.appTheme.headline1(textColor: Colors
                                  .white, fontSize: 20, fontWeight: FontWeight
                                  .normal),),
                          ),
                        ],
                      );
                    }),
              ),
              Padding(
                padding: const EdgeInsets.only(
                    top: 10, left: 18, right: 18, bottom: 10),
                child: Text(
                  '请确认工具位置后将工具按提示位置出入库，请勿乱拿乱放,当柜门关闭时开始扫描',
                  style: AppTheme.appTheme.textStyle(
                      textColor: Colors.white.withOpacity(0.5), fontSize: 18),
                ),
              ),
              Expanded(
                child: BlocConsumer<DeviceBloc, DeviceState>(
                  listener: (_, state) {
                    if (state.readFinish) {
                      Navigator.of(context).pop();
                    }
                    if (state.showForceOperationButton) {
                      FlashHelper.toast(
                          context, '红色标记工具表示未完成操作', MessageType.alert);
                    }
                    if (state.message.isNotEmpty) {
                      FlashHelper.toast(
                          context, state.message, MessageType.alert);
                    }
                  },
                  builder: (context, state) {
                    return ListView.builder(
                      itemBuilder: (context, index) {
                        bool isFind = false;
                        if (state.operateType == 0 &&
                            state.collectList.isNotEmpty) {
                          if (state.collectList
                              .contains(state.handleList[index])) {
                            isFind = true;
                          }
                        }
                        if (state.operateType >0 &&
                            state.collectList.isNotEmpty) {
                          if (!state.collectList
                              .contains(state.handleList[index])) {
                            isFind = true;
                          }
                        }
                        List<ToolData> toolDataList=widget.list.where(
                                (element) =>
                            element.epc ==
                                state.handleList[index]).toList();
                        ToolData? toolData;
                        if(toolDataList.isNotEmpty){
                          toolData=toolDataList[0];
                        }else{
                          toolData=ToolData(id: '未知', imgUrl: "$baseUrl/files/tool.png", toolName: '名称未知', toolSpec: '未知', epc: state.handleList[index], toolCode: '未知', storageSerialNo: '未知', state: 0, lockerPosition: '未知', lockerSerialNo: '未知',factoryNum: '');
                        }
                        return AnimatedContainer(
                          margin: const EdgeInsets.only(
                              left: 18, right: 18, bottom: 15),
                          decoration: BoxDecoration(
                            boxShadow:
                            AppTheme.appTheme.containerBoxShadow(),
                            shape: BoxShape.rectangle,
                            borderRadius: const BorderRadius.all(
                              Radius.circular(15),
                            ),
                            color:
                            AppTheme.appTheme.cardBackgroundColor(),
                          ),
                          duration: const Duration(microseconds: 1200),
                          curve: Curves.elasticIn,
                          child: ToolItemView(
                            isFind: isFind,
                            toolData:toolData,
                          ),
                        );
                      },
                      itemCount: state.handleList.length,
                      // state.handleList.length,
                    );
                  },
                ),
              ),
            ],
          )
        ],
      ),
    );
  }
}

class ToolItemView extends StatelessWidget {
  final ToolData toolData;
  final bool isFind;

  const ToolItemView({required this.toolData, required this.isFind, Key? key})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery
        .of(context)
        .size;
    return Container(
      decoration: BoxDecoration(
          color: isFind ? Colors.green.shade300 : Colors.red.shade300,
          borderRadius: const BorderRadius.all(Radius.circular(15))),
      child: Container(
        margin: const EdgeInsets.only(right: 10),
        decoration: BoxDecoration(
            color: Colors.white.withOpacity(0.9),
            boxShadow: AppTheme.appTheme.containerBoxShadow(),
            borderRadius: const BorderRadius.all(Radius.circular(15))),
        child: Stack(
          children: <Widget>[
            Row(
              children: <Widget>[
                ClipRRect(
                  borderRadius: const BorderRadius.only(
                      topLeft: Radius.circular(15),
                      bottomLeft: Radius.circular(15)),
                  child: SizedBox(
                    width: size.width * 0.22,
                    child: AspectRatio(
                      aspectRatio: 0.8,
                      child: Image.network(
                        toolData.imgUrl,
                        fit: BoxFit.fill,
                      ),
                    ),
                  ),
                ),
                Container(
                  margin: const EdgeInsets.only(left: 10.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Padding(
                        padding: const EdgeInsets.only(top: 5, bottom: 5),
                        child: Text(
                          toolData.toolName,
                          softWrap: true,
                          overflow: TextOverflow.ellipsis,
                          style: AppTheme.appTheme.headline1(
                              fontWeight: FontWeight.w100,
                              fontSize: 18,
                              textColor: Colors.grey),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(top: 5, bottom: 5),
                        child: Text(
                          '规格:${toolData.toolSpec}',
                          style: AppTheme.appTheme.headline2(
                              fontSize: 15.0, fontWeight: FontWeight.w100),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(top: 5, bottom: 5),
                        child: Text(
                          '编码:${toolData.toolCode}',
                          style: AppTheme.appTheme.headline2(
                              fontSize: 15.0, fontWeight: FontWeight.w100),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(top: 5, bottom: 5),
                        child: Text(
                          '编号:${toolData.factoryNum}',
                          style: AppTheme.appTheme.headline2(
                              fontSize: 15.0, fontWeight: FontWeight.w100),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(top: 5, bottom: 5),
                        child: Text(
                          'EPC:${toolData.epc}',
                          style: AppTheme.appTheme.headline2(
                              fontSize: 15, fontWeight: FontWeight.w100),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(top: 5, bottom: 5),
                        child: Text(
                          '存储位置:${toolData.lockerPosition}',
                          maxLines: 100,
                          softWrap: true,
                          overflow: TextOverflow.ellipsis,
                          style: AppTheme.appTheme.headline2(
                              fontSize: 15,
                              textColor: Colors.blue,
                              fontWeight: FontWeight.w100),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            Positioned(
              child: SvgPicture.asset(
                isFind ? 'image/Done.svg' : 'image/loading.svg',
                color: isFind ? Colors.green : Colors.red,
                width: 30,
                height: 30,
              ),
              right: 0,
              top: 0,
            )
          ],
        ),
      ),
    );
  }
}
